package dotdashdot.bradz.trendsettr;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.FacebookException;
import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.Session.Builder;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.OnErrorListener;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.plus.Plus;
import com.ubertesters.sdk.Ubertesters;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ActivityLoginHome extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

	/* Request code used to invoke sign in user interactions. */
	  private static final int RC_SIGN_IN = 0;
	  private static final int REQUEST_CODE_RESOLVE_ERR = 42;
	  /* Client used to interact with Google APIs. */
	  private GoogleApiClient mGoogleApiClient;
	  //private Session.StatusCallback statusCallback = new SessionStatusCallback();
	  /* A flag indicating that a PendingIntent is in progress and prevents
	   * us from starting further intents.
	   */
	  private boolean mIntentInProgress,mSignInClicked,face_book_clicked;
	  private ConnectionResult mConnectionResult;
	  private ClassFonts fonts;
	  private boolean debug_login/* = false*/;
	  private Context self;
	  private ProgressBar login_progress;
	  private LoginButton authButton;
	  private SignInButton googleButton;
	  private Button main_menu,logout;
	  private ApplicationGlobalVars globals;
	  private ClassUberLogger logger;
	  private ClassNetworkHelper helper;
	  
	  Handler myHandler = new Handler() {

	  	    @Override
	  	    public void handleMessage(Message msg) {
	  	        switch (msg.what) {
	  	        case 0:
	  	            break;
	  	        case 4:
	  	        	logout();
		        	break;
	  	        case 5:
	  	        	hide_progress();
		        	break;
	  	        default:
	  	            break;
	  	        }
	  	    }
	  	};
	  	
	  public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    //Ubertesters.initialize(this.getApplication());
	    
	    //This doesn't work if the app is loaded directly to the phone
	    debug_login = "goldfish".equals(Build.HARDWARE);
	    //debug_login = true;
	    
	    globals = ((ApplicationGlobalVars) this.getApplication());
	    logger = new ClassUberLogger("ActivityLoginHome");
	    setContentView(R.layout.activity_login_home);
	    fonts = new ClassFonts(this.getAssets());
	    TextView title = (TextView) this.findViewById(R.id.title_text);
		title.setTypeface(fonts.get_font("italic"));
		
		self = this;
        
        //Google+
	    mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(Plus.API, null)
        .addScope(Plus.SCOPE_PLUS_LOGIN)
        .build();
	    
	    face_book_clicked = false;
	    
	    helper = new ClassNetworkHelper(this,((ApplicationGlobalVars) this.getApplication()));
	    
	    update_buttons();
	    logger.info("OnCreate finished");
	    
	    /*ArrayList<NameValuePair> post_data = new ArrayList<NameValuePair>();
    	post_data.add(new BasicNameValuePair("trendName","Celtics"));
    	ClassNetworkHelper helper = new ClassNetworkHelper(self,globals);
    	helper.post_network(post_data, "/downvote",myHandler);*/
	  }

  private void update_buttons(){
	  
	  login_progress = (ProgressBar) findViewById(R.id.login_progress);
	  
	  authButton = (LoginButton) findViewById(R.id.sign_in_button_facebook);
	  
	  authButton.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
        	  
        	  logger.info("Facebook clicked");
        	  
        	  face_book_clicked = true;
        	  
        	  login_progress.setVisibility(View.VISIBLE);
        	  
        	  Session currentSession = Session.getActiveSession();
        	    if (currentSession == null || currentSession.getState().isClosed()) {
        	    	logger.info("Making new Facebook session object...");
        	        Session session = new Session.Builder(self).build();
        	        Session.setActiveSession(session);
        	        currentSession = session;
        	    }

        	    if (currentSession.isOpened()) {
        	    	logger.info("Opening current Facebook session...");
        	    	//currentSession.closeAndClearTokenInformation();
        	    	open_active_session();
        	        // Do whatever u want. User has logged in

        	    } else if (!currentSession.isOpened()) {
        	        // Ask for username and password
            	    logger.info("Opening new Facebook session...");
        	        OpenRequest op = new Session.OpenRequest((Activity) self);

        	        op.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
        	        op.setCallback(null);

        	        List<String> permissions = new ArrayList<String>();
        	        permissions.add("basic_info");
        	        permissions.add("user_status");
        	        permissions.add("email");
        	        permissions.add("user_birthday");
        	        op.setPermissions(permissions);

        	        Session session = new Builder(ActivityLoginHome.this).build();
        	        Session.setActiveSession(session);
        	        session.openForRead(op);
        	    }
          }
      });
	  
	  googleButton = (SignInButton) findViewById(R.id.sign_in_button_google);
	  
	  googleButton.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
        	logger.info("Google+ clicked");
        	face_book_clicked = false;
        	login_progress.setVisibility(View.VISIBLE);
          	if (!mGoogleApiClient.isConnecting()) {
          		logger.info("Connecting to Google+");
      		    mSignInClicked = true;
      		    mGoogleApiClient.connect();
          	}else{
          		logger.error("Unexpected error occured with Google+ API");
          		Toast.makeText(self, "An unexpected error has occurred with the Google+ API", 1000).show();
          		login_progress.setVisibility(View.GONE);
          	}
          }
	    });
	  
	  main_menu = (Button) findViewById(R.id.main_menu_button);
	  logout = (Button) findViewById(R.id.log_out_button);
	  
	  logout.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
        	  	logger.info("Logout clicked");
        	  	login_progress.setVisibility(View.VISIBLE);
          		//ClassNetworkHelper helper = new ClassNetworkHelper(self,globals);
        		helper.log_out_network(myHandler);
          }
	    });
	  
	  main_menu.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
        	  Intent myIntent = new Intent(self, ActivityHome.class);
        	  self.startActivity(myIntent);
          }
	    });
  }
  
  private void hide_progress(){
	  login_progress.setVisibility(View.GONE);
  }
  
  private void logout(){
	  	logger.info("Logging out");
	  	hide_progress();
	  	authButton.setVisibility(View.VISIBLE);
		googleButton.setVisibility(View.VISIBLE);
		logout.setVisibility(View.GONE);
		main_menu.setVisibility(View.GONE);
		globals.invalidate_credentials();
  }
	  
  private void resolveSignInError() {
	  logger.info("Resolving Signin Error");
	  if (mConnectionResult != null && mConnectionResult.hasResolution()) {
	    try {
	      logger.warning("Connection failed first attempt. Retrying...");
	      mIntentInProgress = true;
	      mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
	    } catch (SendIntentException e) {
	      // The intent was canceled before it was sent.  Return to the default
	      // state and attempt to connect to get an updated ConnectionResult.
	      logger.error("Connection Error: " + e);
	      mIntentInProgress = false;
	      mGoogleApiClient.connect();
	    }
	  }
	}
	  
  @Override
  protected void onStart() {
    super.onStart();
    //mGoogleApiClient.connect();
    logger.info("OnStart called");
    if(debug_login){
    	logger.warning("Debug Login = true. Using test data. Login buttons disabled...");
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		/*ClassNetworkHelper helper = new ClassNetworkHelper(self,globals);
		pairs.add(new BasicNameValuePair("username", "Brad Zimmerman"));
		pairs.add(new BasicNameValuePair("email", "mauvemoonman@gmail.com"));
		pairs.add(new BasicNameValuePair("service", "Google+"));
		pairs.add(new BasicNameValuePair("location", "Somerville,Massachusetts"));
		pairs.add(new BasicNameValuePair("gender", "male"));
		pairs.add(new BasicNameValuePair("birthday", "08/12/1987"));
		pairs.add(new BasicNameValuePair("token", "test_token"));
		pairs.add(new BasicNameValuePair("password", ""));*/
		
		pairs.add(new BasicNameValuePair("username", "Squanchy Squanch"));
		pairs.add(new BasicNameValuePair("email", "squanchy@yahoo.com"));
		pairs.add(new BasicNameValuePair("service", "Google+"));
		pairs.add(new BasicNameValuePair("location", "Detroit,Michigan"));
		pairs.add(new BasicNameValuePair("gender", "male"));
		pairs.add(new BasicNameValuePair("birthday", "04/12/1980"));
		pairs.add(new BasicNameValuePair("token", "test_token"));
		pairs.add(new BasicNameValuePair("password", ""));
		
		helper.log_into_network(ActivityHome.class, pairs, debug_login);
		
		//List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		
	}
  }
  
  @Override
  protected void onResume() {
    super.onResume();
    //Turn off the loading circle if we come back to this screen...
    logger.info("OnResume Called");
    login_progress.setVisibility(View.GONE);
    main_menu.setVisibility(View.GONE);
    if(globals.credentials_loaded()){
    	authButton.setVisibility(View.GONE);
    	googleButton.setVisibility(View.GONE);
    	logout.setVisibility(View.VISIBLE);
    	main_menu.setVisibility(View.VISIBLE);
    }else{
    	authButton.setVisibility(View.VISIBLE);
    	googleButton.setVisibility(View.VISIBLE);
    	logout.setVisibility(View.GONE);
    	main_menu.setVisibility(View.GONE);
    	
    }
    //mGoogleApiClient.connect();
  }
  
  @Override
  protected void onStop() {
    super.onStop();
    logger.info("OnStop Called");
    if (mGoogleApiClient.isConnected()) {
      mGoogleApiClient.disconnect();
    }
  }
  
	@Override
	public void onConnectionFailed(ConnectionResult result) {
		logger.warning("Google+ Connection Failed!");
		logger.info(result.toString());
		
		
		if (!mIntentInProgress && result.hasResolution()) {
		    try {
		      mIntentInProgress = true;
		      startIntentSenderForResult(result.getResolution().getIntentSender(),REQUEST_CODE_RESOLVE_ERR, null, 0, 0, 0);
		    } catch (SendIntentException e) {
		      // The intent was canceled before it was sent.  Return to the default
		      // state and attempt to connect to get an updated ConnectionResult.
		      mIntentInProgress = false;
		      mGoogleApiClient.connect();
		    }
		  }
		
		
		/*if (!mIntentInProgress) {
			mConnectionResult = result;
			if (mSignInClicked) {
			      resolveSignInError();
			    }
		  }
		*/
		/*if (result.hasResolution()) {
	        try {
	            result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
	        } catch (SendIntentException e) {
	        	mGoogleApiClient.connect();
	        }
	    }
	    // Save the result and resolve the connection failure upon a user click.
	    mConnectionResult = result;*/
	}

	//public void get_server_id(String account_name, String user_name, String service, String location, String gender, String birthdate, String profile_pic, String token){
	public void get_server_id(Map<String, String> map){
		
		login_progress.setVisibility(View.GONE);
		
		logger.info("Logged into server. Acquiring credentials...");
		logger.info("account_name: " + map.get("account_name"));
		logger.info("user_name: " + map.get("user_name"));
		logger.info("service: " + map.get("service"));
		logger.info("location: " + map.get("location"));
		logger.info("gender: " + map.get("gender"));
		logger.info("birthday: " + map.get("birthdate"));
		logger.info("picture: " + map.get("picture"));
		logger.info("token: " + map.get("token"));
		logger.info("Logged into server. End of credentials...");
		
		Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();	
		
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("email", map.get("account_name")));
		pairs.add(new BasicNameValuePair("username", map.get("user_name")));
		pairs.add(new BasicNameValuePair("service", map.get("service")));
		pairs.add(new BasicNameValuePair("location", map.get("location")));
		pairs.add(new BasicNameValuePair("gender", map.get("gender")));
		pairs.add(new BasicNameValuePair("birthday", map.get("birthdate")));
		pairs.add(new BasicNameValuePair("token", map.get("token")));
		pairs.add(new BasicNameValuePair("picture", map.get("picture")));
		pairs.add(new BasicNameValuePair("password", ""));
		//ClassHttpHelper helper = new ClassHttpHelper("http://dsaprykin-trendsettr.jit.su");
		
		//ClassNetworkHelper helper = new ClassNetworkHelper(this,((ApplicationGlobalVars) this.getApplication()));
		helper.log_into_network(ActivityHome.class, pairs, debug_login);
	}
	
	@Override
	public void onConnected(Bundle connectionHint) {
		
		mSignInClicked = false;
		logger.info("Logged in. Printing info...");
		logger.info("account_name: " + Plus.AccountApi.getAccountName(mGoogleApiClient));
		logger.info("user_name: " + Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getDisplayName());
		logger.info("service: " + "Google+");
		logger.info("location: " + Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getCurrentLocation());
		 
		int gender = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getGender();
		logger.info("gender int: " + gender);
		String gender_string = gender==0?"male":(gender==1?"female":"other");
		 
		logger.info("gender: " + gender_string);
		logger.info("birthday: " + Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getBirthday());
		logger.info("picture: " + Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getImage().getUrl());
		logger.info("Logged in. End of info...");
		 
		GetTokenAsync token_finder = new GetTokenAsync(Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getImage().getUrl(),
				Plus.AccountApi.getAccountName(mGoogleApiClient),
				 Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getDisplayName(),
				 "Google+",Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getCurrentLocation(),
				 gender_string,
				 Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getBirthday(),
				 mGoogleApiClient);
		
		//Make sure that we have a token to give our server...
		//Basically makes us harder to hack
		token_finder.execute();
		
		 //If the user connects to the google play servers, navigate to the home page
		 /*get_server_id(Plus.AccountApi.getAccountName(mGoogleApiClient),
				 Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getDisplayName(),
				 "Google+",Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getCurrentLocation(),
				 gender_string,
				 Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getBirthday(),token);*/
	}

	@Override
	public void onConnectionSuspended(int cause) {
		mGoogleApiClient.connect();
	}
	
	@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }
	
	@Override
	protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
    	super.onActivityResult(requestCode, responseCode, intent);
    	
		logger.info("OnActivityResult");
		logger.info("RequestCode: " + requestCode);
		logger.info("ResponseCode: " + responseCode);
		
		login_progress.setVisibility(View.GONE);
		
        //The callback for the google+ login
		if (requestCode == RC_SIGN_IN || requestCode == REQUEST_CODE_RESOLVE_ERR) {
		    if (responseCode != RESULT_OK) {
		      mSignInClicked = false;
		    }
		    mIntentInProgress = false;
		    if (!mGoogleApiClient.isConnecting()) {
		      logger.info("Trying to connect to Google+");
		      mGoogleApiClient.connect();
		    }
		}
		
		if(face_book_clicked){
			if (Session.getActiveSession() != null)
		        Session.getActiveSession().onActivityResult(this, requestCode,
		        		responseCode, intent);
	
		    Session currentSession = Session.getActiveSession();
		    if (currentSession == null || currentSession.getState().isClosed()) {
		        Session session = new Session.Builder(self).build();
		        Session.setActiveSession(session);
		        currentSession = session;
		    }
	
		    if (currentSession.isOpened()) {
		    	logger.info("Opening active Facebook session...");
		    	open_active_session();
		    }
		}
		
	}
	
	private void open_active_session(){
		Session.openActiveSession(this, true, new Session.StatusCallback() {

            @Override
            public void call(final Session session, SessionState state,
                    Exception exception) {

            	if(session != null){
            		logger.info("Facebook Session: " + session.toString());
            		logger.info("Facebook Session Closed: " + String.valueOf(session.isClosed()));
  		      }else{
  		    	  logger.info("No Facebook Session");
  		      }
  		      if(state != null){
  		    	logger.info("State: " + state.toString());
  		      }else{
  		    	logger.info("No State");
  		      }
  		      if(exception != null){
  		    	logger.error("Facebook Exception: " + exception.getMessage());
  		      }else{
  		    	logger.info("No Facebook Exceptions");
  		      }
            	
                if (session.isOpened()) {
                	
                	logger.info("Facebook Session Opened...");

                    Request.executeMeRequestAsync(session,
                            new Request.GraphUserCallback() {

                                @Override
                                public void onCompleted(GraphUser user,Response response) {	
                                	logger.info("Facebook Logged in");
                                    if (user != null) {
                                    	
                                    	logger.info("Returned Data...");
	                                	for(Map.Entry<String, Object> map : user.asMap().entrySet()){
	                                		logger.info("Key: " + map.getKey());
	                                		logger.info(" Value: " + String.valueOf(map.getValue()));
	                                	}
	                                	
	                                	JSONObject home_location = (JSONObject) user.asMap().get("location");
	                           
	                                	String home_string;
	                                	
										try {
											home_string = home_location.get("name").toString();
										} catch (JSONException e) {
											// TODO Auto-generated catch block
											home_string = "Error";
											logger.error("JSON Error: " + e);
											e.printStackTrace();
										}
	                                	
										Map<String, String> map = new HashMap<String, String>();
										map.put("account_name", (String) response.getGraphObject().getProperty("email"));
										map.put("user_name", (String) user.asMap().get("username"));
										map.put("service", "Facebook");
										map.put("location", home_string);
										map.put("gender", (String) user.asMap().get("gender"));
										map.put("birthdate", (String) user.asMap().get("birthday"));
										map.put("token", Session.getActiveSession().getAccessToken());
										
										get_picture_facebook(map);

                                    }else{
                                    	Toast.makeText(self, "Can't establish a reliable connection to the server.", Toast.LENGTH_LONG).show();
                                    }
                                }
                            });
                }
            }
        });
	}
	
	private void get_picture_facebook(final Map<String, String> map){
		Bundle params = new Bundle();
		params.putBoolean("redirect", false);
		//params.putString("height", "200");
		params.putString("type", "normal");
		//params.putString("width", "200");
		/* make the API call */
		new Request(
			Session.getActiveSession(),
		    "/me/picture",
		    params,
		    HttpMethod.GET,
		    new Request.Callback() {
		        public void onCompleted(Response response) {
		            /* handle the result */
		        	logger.info("Printing Response");
		        	if(response.getError() == null){
						try {
							JSONObject json = response.getGraphObject().getInnerJSONObject().getJSONObject("data");
							logger.info("Found picture. Returning: " + json.getString("url"));
							map.put("picture", json.getString("url"));
						} catch (JSONException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
		        	}else{
		        		logger.warning("Error encountered loading facebook picture");
		        		map.put("picture", "");
		        	}
		        	get_server_id(map);
		        	//logger.info((String) response.getGraphObject().getProperty("url"));
		        	//get_server_id(map);
		        }
		    }
		).executeAsync();
	}
	
	private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
        	update_buttons();
        }
    }
	
	public class GetTokenAsync extends AsyncTask<String, String, String>
    {

		String token;
		String account_name; 
		String user_name; 
		String service;
		String location; 
		String gender;
		String birthdate; 
		String account_pic;
		GoogleApiClient api_client;
		
		GetTokenAsync(String account_pic, String account_name, String user_name, String service, String location, String gender, String birthdate, GoogleApiClient api_client){
			this.account_pic = account_pic;
			this.account_name = account_name;
			this.user_name = user_name;
			this.service = service;
			this.location = location;
			this.gender = gender;
			this.birthdate = birthdate;
			token = null;
			this.api_client = api_client;
			logger.info("Google+ Token Parsing Initialized");
		}
		
        @Override
        protected void onPreExecute()
            {
                super.onPreExecute();

            }

        @Override
        protected String doInBackground(String... params)
            {
                String scope = "oauth2:" + Scopes.PLUS_LOGIN;
                
                try
                    {
                        token = GoogleAuthUtil.getToken(self, account_name, scope);
                    }
                catch (UserRecoverableAuthException e)
                    {
                		logger.error( "UserRecoverableAuthException");
                        e.printStackTrace();
                        //Toast.makeText(self, "UserRecoverableAuthException!", 1000).show();
                        token = null;
                    }
                catch (IOException e)
                    {
                		logger.error( "IOException");
                        e.printStackTrace();
                        //Toast.makeText(self, "IOException!", 1000).show();
                        token = null;
                    }
                catch (GoogleAuthException e)
                    {
                		logger.error( "GoogleAuthException");
                        e.printStackTrace();
                        //Toast.makeText(self, "GoogleAuthException!", 1000).show();
                        token = null;
                    }
                catch (Exception e)
                    {
                		logger.error( "Exception");
                        e.printStackTrace();
                        //Toast.makeText(self, "Exception: " + e.getMessage(), 1000).show();
                        token = null;
                    }
        		//token = "Blank_token";
			
                return null;
            }

        @Override
        protected void onPostExecute(String result)
            {
                super.onPostExecute(result);
                
                //Make sure that we have a server token. Otherwise dont bother
                if(token != null){
                	logger.info("Received Google+ Token: " + token);
                	
                	Map<String, String> map = new HashMap<String, String>();
                	
					map.put("account_name", account_name);
					map.put("user_name", user_name);
					map.put("service", service);
					map.put("location", location);
					map.put("gender", gender);
					map.put("birthdate", birthdate);
					map.put("picture", account_pic);
					map.put("token", token);
					
					get_server_id(map);
                }else{
                	logger.error("Couldn't verify access token!");
                	Toast.makeText(self, "Could not verify access token!", 1000).show();
                }
            }

    }
}
